package cn.goour.web

import cn.goour.web.sys.entity.Admin
import cn.goour.web.sys.entity.LoginApiKey
import cn.goour.web.sys.entity.Role
import cn.goour.web.sys.entity.RoleGroup
import cn.goour.web.sys.entity.type.LoginType
import cn.goour.web.sys.repository.AdminRepository
import cn.goour.web.sys.repository.LoginApiKeyRepository
import cn.goour.web.sys.repository.RoleGroupRepository
import cn.goour.web.sys.repository.RoleRepository
import encrypt
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Configuration
import org.springframework.stereotype.Controller
import javax.annotation.PostConstruct
import javax.servlet.ServletContext

@Configuration
@Controller
open class Initialized {

    @Autowired
    private lateinit var repository: AdminRepository
    @Autowired
    private lateinit var roleRepository: RoleRepository
    @Autowired
    private lateinit var roleGroupRepository: RoleGroupRepository
    @Autowired
    private lateinit var loginApiKeyRepository: LoginApiKeyRepository

    @PostConstruct
    fun post() {
        logger.info("PostConstruct ${this.javaClass.simpleName}....")
        println("PostConstruct ${this.javaClass.simpleName}....")
        initLoginKey()
        initAdmin()
    }

    private fun initLoginKey() {
        logger.info("初始化第三方登录参数 ...")
        var key = LoginApiKey(appId = "991364614", appSecret = "c0caa121617670824d80947398a63f00", redirectUri = "http://goour.cn:8081/login/weiBoLogin", scope = "", loginType = LoginType.WeiBo)
        loginApiKeyRepository.save(key)
        key = LoginApiKey(appId = "wx325553fdf168315e", appSecret = "d4624c36b6795d1d99dcf0547af5443d", redirectUri = "http://192.168.199.20:8081/login/weiXinLogin", scope = "snsapi_userinfo", loginType = LoginType.WeiXin)
        loginApiKeyRepository.save(key)
        key = LoginApiKey(appId = "wx325553fdf168315e", appSecret = "d4624c36b6795d1d99dcf0547af5443d", redirectUri = "http://192.168.199.20:8081/login/weiXinLogin", scope = "snsapi_userinfo", loginType = LoginType.WeiXinWeb)
        loginApiKeyRepository.save(key)
        key = LoginApiKey(appId = "914a4ad591a02c69", appSecret = "c1ce7bad07f3fd1002b22bd6f796b0f7", redirectUri = "http://dser.top:8081/login/yiBanLogin", scope = "", loginType = LoginType.YiBan)
        loginApiKeyRepository.save(key)
        key = LoginApiKey(appId = "101435522", appSecret = "0e523eb0b83abcc33d421119618197f3", redirectUri = "http://dser.top:8081/login/qqLogin", scope = "get_user_info,add_topic,add_one_blog,add_album,upload_pic,list_album,add_share,check_page_fans,add_t,add_pic_t,del_t,get_repost_list,get_info,get_other_info,get_fanslist,get_idollist,add_idol,del_ido,get_tenpay_addr"
                , loginType = LoginType.QQ)
        loginApiKeyRepository.save(key)
    }

    private fun initAdmin() {
        logger.info("初始化管理员用户 ...")

        var admin = repository.getByUsername("admin")
        if (admin == null) {
            val adminGroupRoles = ArrayList<Role>()
            Role.roles.forEach { _, u ->
                u.forEachIndexed { index, role ->
                    val re = roleRepository.save(role)
                    u[index] = re
                    adminGroupRoles.add(re)
                }
            }
            var adminGroup = RoleGroup(name = "高级管理员权限",roles = adminGroupRoles)
            adminGroup = roleGroupRepository.save(adminGroup)

            Role.roles.forEach { t, u ->
                val group = RoleGroup(name = t, roles = u)
                roleGroupRepository.save(group)
            }

            admin = Admin(name = "隐藏超级管理员", username = "root", password = "root".encrypt(), email = "root@qq.com", vip = 0,roleGroup = adminGroup)
            repository.save(admin)

            admin = Admin(name = "高级管理员", username = "admin", password = "admin".encrypt(), email = "admin@qq.com",roleGroup = adminGroup)
            repository.save(admin)


        }
        admin = repository.getByUsername("admin")
        println("保存到数据库后，重新获取的结果：$admin")
    }

    companion object {
        private val logger = LoggerFactory.getLogger(Initialized::class.java)
        val slPrefix: String = "sitesLogin"

        fun onStartup(servletContext: ServletContext?) {
            logger.info("onStartup Initialized...")
            println("onStartup Initialized....")
            if (servletContext == null) {
                logger.info("ServletContext参数为空，不进行操作")
                return
            } else {

                servletContext.setInitParameter("wurfl", "wurfl.zip")
                servletContext.setInitParameter("wurflUpdateUrl", "https://data.scientiamobile.com/rkrtm/wurfl.zip")

                // 默认开启第三方登录
                servletContext.setAttribute(slPrefix + LoginType.Email, true)
                servletContext.setAttribute(slPrefix + LoginType.Username, true)
                servletContext.setAttribute(slPrefix + LoginType.Phone, true)
                servletContext.setAttribute(slPrefix + LoginType.QQ, true)
                servletContext.setAttribute(slPrefix + LoginType.WeiBo, true)
                servletContext.setAttribute(slPrefix + LoginType.WeiXin, true)
                servletContext.setAttribute(slPrefix + LoginType.WeiXinWeb, true)
                servletContext.setAttribute(slPrefix + LoginType.YiBan, true)

                servletContext.setAttribute("sites_title", "数字服务网")

            }
        }

        @Deprecated("这是一个可能不使用的方法")
        fun startListenerWurfl(servletContext: ServletContext) {
            servletContext.addListener(com.scientiamobile.wurfl.core.web.WURFLServletContextListener())
            servletContext.setInitParameter("wurfl", "classpath:/wurfl.zip")
            servletContext.setInitParameter("wurflUpdateUrl", "https://data.scientiamobile.com/rkrtm/wurfl.zip")
            servletContext.setInitParameter("wurflEngineTarget", "performance")
            servletContext.setInitParameter("wurflUserAgentPriority", "OverrideSideloadedBrowserUserAgent")
            servletContext.setInitParameter("capability-filter", """
                is_wireless_device
				preferred_markup
				xhtml_support_level
				xhtmlmp_preferred_mime_type
				device_os
				device_os_version
				is_tablet
				mobile_browser_version
				pointing_method
				mobile_browser
				resolution_width
				resolution_height
				ux_full_desktop
				is_smarttv
				can_assign_phone_number
				marketing_name
				brand_name
				model_name
				mobile_browser_version
            """.trimIndent())
        }
    }
}